extends CharacterBody2D

# 基础属性
@export var speed = 200.0
@export var max_health = 100
var current_health = 100

# 升级相关属性
@export var experience = 0
@export var level = 1
@export var experience_needed = 10

# 新增属性系统
var armor = 0  # 护甲值，减少受到的伤害
var pickup_range = 1.0  # 拾取范围倍率
var health_regen = 0  # 每秒恢复生命值
var crit_chance = 0.0  # 暴击几率 (0.0-1.0)
var crit_damage = 2.0  # 暴击伤害倍率
var exp_bonus = 0.0  # 经验获取加成 (0.0-1.0+)
var dodge_chance = 0.0  # 闪避几率 (0.0-1.0)

# 武器相关
var active_weapons = []
@onready var weapon_container = $WeaponContainer
@onready var pickup_area = $PickupArea

# 计时器
var regen_timer = 0.0

# 信号
signal health_changed(new_health, max_health)
signal experience_changed(new_xp, needed_xp, current_level)
signal leveled_up(current_level)
signal player_stats_changed(stats_dict)  # 新增信号，用于更新UI显示

func _ready():
	add_to_group("player")
	current_health = max_health
	emit_signal("health_changed", current_health, max_health)
	emit_signal("experience_changed", experience, experience_needed, level)
	
	# 初始化已有武器
	for weapon in weapon_container.get_children():
		if weapon.has_method("set_owner_player"):
			weapon.set_owner_player(self)
			active_weapons.append(weapon)
	
	# 发送初始状态信号
	emit_player_stats()

func _physics_process(delta):
	# --- Movement ---
	var direction = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	velocity = direction.normalized() * speed
	move_and_slide()
	
	# --- Check for enemy collision ---
	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		if collision.get_collider().is_in_group("enemies"):
			# 尝试闪避
			if randf() < dodge_chance:
				print("Player dodged attack!")
				continue
			
			# 计算伤害（考虑护甲）
			var damage_amount = max(1, 10 - armor)  # 最小伤害为1
			take_damage(damage_amount)
	
	# --- 生命恢复系统 ---
	if health_regen > 0 and current_health < max_health:
		regen_timer += delta
		if regen_timer >= 1.0:  # 每秒恢复
			regen_timer = 0.0
			heal(health_regen)

func take_damage(amount):
	current_health = max(0, current_health - amount)
	emit_signal("health_changed", current_health, max_health)
	print("Player took damage, health: ", current_health)
	if current_health <= 0:
		game_over()

func heal(amount):
	current_health = min(max_health, current_health + amount)
	emit_signal("health_changed", current_health, max_health)
	print("Player healed for ", amount, ", health: ", current_health)

func add_experience(amount):
	# 应用经验加成
	var bonus_amount = amount * (1.0 + exp_bonus)
	experience += bonus_amount
	print("Gained XP: ", bonus_amount, " | Total: ", experience, "/", experience_needed)
	while experience >= experience_needed:
		level_up()
	emit_signal("experience_changed", experience, experience_needed, level)

func level_up():
	experience -= experience_needed
	level += 1
	experience_needed = int(experience_needed * 1.5)  # 增加下一级所需经验
	print("LEVEL UP! Reached Level: ", level)
	# 暂停游戏并显示升级界面
	get_tree().paused = true
	emit_signal("leveled_up", level)  # UI监听此信号

func apply_upgrade(upgrade_id):
	print("Applying upgrade: ", upgrade_id)
	match upgrade_id:
		# 武器相关升级
		"add_knife":
			add_new_weapon("res://BasicKnife.tscn")
		"upgrade_knife_damage":
			upgrade_existing_weapon("BasicKnife", "damage", 5)
		"upgrade_knife_speed":
			upgrade_existing_weapon("BasicKnife", "speed", 0.1)
		"upgrade_knife_range":
			upgrade_existing_weapon("BasicKnife", "range", 50.0)
		"add_fire_staff":
			add_new_weapon("res://FireStaff.tscn")
		"add_ice_wand":
			add_new_weapon("res://IceWand.tscn")
		"add_lightning_chain":
			add_new_weapon("res://LightningChain.tscn")
		"add_spinning_axe":
			add_new_weapon("res://SpinningAxe.tscn")
			
		# 属性相关升级
		"increase_health":
			max_health += 20
			current_health += 20
			emit_signal("health_changed", current_health, max_health)
		"increase_speed":
			speed += 20
			print("Speed increased to: ", speed)
		"increase_armor":
			armor += 2
			print("Armor increased to: ", armor)
		"increase_pickup_range":
			pickup_range += 0.2
			update_pickup_range()
			print("Pickup range increased to: ", pickup_range)
		"increase_health_regen":
			health_regen += 1
			print("Health regeneration increased to: ", health_regen)
		"increase_crit_chance":
			crit_chance += 0.05
			crit_chance = min(crit_chance, 0.7)  # 最大70%暴击率
			print("Critical chance increased to: ", crit_chance * 100, "%")
		"increase_crit_damage":
			crit_damage += 0.5
			print("Critical damage multiplier increased to: ", crit_damage)
		"increase_exp_gain":
			exp_bonus += 0.1
			print("Experience bonus increased to: ", exp_bonus * 100, "%")
		"increase_dodge":
			dodge_chance += 0.05
			dodge_chance = min(dodge_chance, 0.5)  # 最大50%闪避率
			print("Dodge chance increased to: ", dodge_chance * 100, "%")
		_:
			print("Unknown upgrade selected: ", upgrade_id)
	
	# 更新玩家状态UI
	emit_player_stats()
	
	# 选择后恢复游戏
	get_tree().paused = false

func add_new_weapon(weapon_scene_path):
	var weapon_scene = load(weapon_scene_path)
	if weapon_scene:
		var new_weapon = weapon_scene.instantiate()
		weapon_container.add_child(new_weapon)
		if new_weapon.has_method("set_owner_player"):
			new_weapon.set_owner_player(self)
		active_weapons.append(new_weapon)
		print("Added new weapon: ", new_weapon.name)
	else:
		print("Failed to load weapon scene: ", weapon_scene_path)

func upgrade_existing_weapon(weapon_name_or_type, stat_to_upgrade, value):
	for weapon in active_weapons:
		if weapon.name.contains(weapon_name_or_type):
			if weapon.has_method("upgrade_stat"):
				weapon.upgrade_stat(stat_to_upgrade, value)
				print("Upgraded ", weapon.name, " stat: ", stat_to_upgrade)
			else:
				print("Weapon ", weapon.name, " doesn't have upgrade_stat method")

func update_pickup_range():
	# 更新拾取范围
	if pickup_area and pickup_area.has_node("CollisionShape2D"):
		var collision_shape = pickup_area.get_node("CollisionShape2D")
		var original_scale = Vector2(1, 1)  # 假设原始缩放为1
		collision_shape.scale = original_scale * pickup_range

func emit_player_stats():
	# 创建包含所有玩家状态的字典
	var stats = {
		"level": level,
		"health": current_health,
		"max_health": max_health,
		"speed": speed,
		"armor": armor,
		"pickup_range": pickup_range,
		"health_regen": health_regen,
		"crit_chance": crit_chance,
		"crit_damage": crit_damage,
		"exp_bonus": exp_bonus,
		"dodge_chance": dodge_chance
	}
	emit_signal("player_stats_changed", stats)

func game_over():
	print("GAME OVER")
	# 冻结玩家，显示游戏结束界面等
	get_tree().paused = true

# 连接PickupArea的area_entered信号到此函数
func _on_pickup_area_area_entered(area):
	if area.is_in_group("experience_orbs"):
		add_experience(area.xp_amount)
		area.queue_free()  # 移除经验球

# 获取武器的暴击信息
func get_crit_info():
	return {"chance": crit_chance, "multiplier": crit_damage}
